import GameMgr from './GameManager'

export default class MusicMgr {
  private _bgmId: number = -1
  private _bgmVolume: number = 1
  private _effectVolume: number = 1

  init() {
    cc.game.on(cc.game.EVENT_HIDE, () => {
      cc.audioEngine.pauseAll()
    })
    cc.game.on(cc.game.EVENT_SHOW, () => {
      cc.audioEngine.resumeAll()
    })
  }

  playBgm(url: string) {
    const audioUrl = 'music/' + url
    // 如果当前已经在播放bgm了 那么切换bgm
    if (this._bgmId >= 0) {
      cc.audioEngine.stop(this._bgmId)
    }
    const clip = GameMgr.instance.audioClip[audioUrl]
    if (clip) {
      this._bgmId = cc.audioEngine.play(clip, true, this._bgmVolume)
    } else {
      cc.resources.load(audioUrl, (err, clip: cc.AudioClip) => {
        if (!err) {
          this._bgmId = cc.audioEngine.play(clip, true, this._bgmVolume)
          GameMgr.instance.audioClip[audioUrl] = clip
        } else {
          console.error(err, audioUrl, '音乐加载失败')
        }
      })
    }
  }

  playEffect(url: string) {
    const audioUrl = 'music/' + url
    const clip = GameMgr.instance.audioClip[audioUrl]
    if (clip) {
      cc.audioEngine.play(clip, false, this._effectVolume)
    } else {
      cc.resources.load(audioUrl, (err, clip: cc.AudioClip) => {
        if (!err) {
          cc.audioEngine.play(clip, false, this._effectVolume)
          GameMgr.instance.audioClip[audioUrl] = clip
        } else {
          console.error(err, audioUrl, '音效加载失败')
        }
      })
    }
  }

  setBgmVolume(v: number) {
    if (v > 1) {
      v = 1
    }
    this._bgmVolume = v
    cc.audioEngine.setVolume(this._bgmId, v)
  }

  setEffectVolume(v: number) {
    if (v > 1) {
      v = 1
    }
    this._effectVolume = v
  }
}
